package Cau1;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class UDPClient {

	DatagramSocket socket;
	DatagramPacket packet;
	InetAddress ia;
	
	public UDPClient(){
		try {
			socket = new DatagramSocket();
			ia = InetAddress.getLocalHost();
		} 
		catch (SocketException e) { System.out.print("Can not start client socket"); }
		catch (UnknownHostException e) {System.out.print("Unknow host"); }
	}
	public void run(){
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		boolean cont = true;
		while(cont){
			 
			try {
				System.out.print("Dien ap: ");
				float da =  Float.parseFloat(br.readLine());
				System.out.print("Dong dien: ");
				float dd = Float.parseFloat(br.readLine());
				
				NguonDien nd = new NguonDien(da, dd);
				write2Server(nd);
				
			} catch (NumberFormatException e) {	System.out.print("Ban da nhap sai ");}
		      catch (IOException e) {e.printStackTrace(); }
		}
		System.out.print("Ket thuc qua trinh");
	}
	
	public void write2Server(NguonDien nd){
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			ObjectOutputStream os = new ObjectOutputStream(out);
			os.writeObject(nd);
			packet = new DatagramPacket(out.toByteArray(), out.size(), ia, 5000);
			socket.send(packet);
		} catch (IOException e) {e.printStackTrace(); }
	}
	public static void main(String[] args) {
		UDPClient client = new UDPClient();
		client.run();
	}

}
